/**
 *
 * © Bahadir Zeren 2011
 * bzeren@gmail.com
 * No warranties, express or implied, are made for this program.
 *
 */

package org.baatar.opt.genetic.impl.prmopt;

import bsh.Interpreter;
import java.util.ArrayList;
import org.baatar.opt.genetic.chromosome.IChromosome;
import org.baatar.opt.genetic.chromosome.IChromosomeFactory;

/**
 *
 * Chromosome factory class for boolean structured chromosomes.
 *
 */
public class ChromosomeFactory implements IChromosomeFactory<Boolean> {

    private int chromosomeLength = 0;
    private ArrayList<ParamInfo> paramInfos = null;
    private String fitnessScript = null;
    private Interpreter interpreter = new Interpreter();

    public ChromosomeFactory(ArrayList<ParamInfo> paramInfos,
                                String fitnessScript) {
        this.paramInfos = paramInfos;
        for (int i = 0; i < paramInfos.size(); i++)
            chromosomeLength += paramInfos.get(i).getBitSize();
        this.fitnessScript = fitnessScript;
    }

    public synchronized double runFitnessScript(ArrayList<Double> params) {
        try {
            for (int i = 0; i < params.size(); i++) {
                interpreter.set(paramInfos.get(i).getParamName(), params.get(i));
            }
            return (Double) interpreter.eval(fitnessScript);
        } catch(Exception ex) {
            return 0.0;
        }
    }

    @Override
    public IChromosome<Boolean> createChromosome() {
        return new Chromosome(this);
    }

    @Override
    public int getChromosomeLength() {
        return chromosomeLength;
    }

    /**
     * @return the paramInfos
     */
    public ArrayList<ParamInfo> getParamInfos() {
        return paramInfos;
    }

}
